<!--
 * @Author: chenhuanhuan 2925102113@qq.com
 * @Date: 2024-12-11 10:09:37
 * @LastEditors: wuheng wuheng@szhbzc.com
 * @LastEditTime: 2025-03-08 16:28:12
 * @FilePath: \hbzc-groupmeal-center-web\src\centerViews\basicInformation\skuManage\skuInformation\index.vue
-->
<template>
  <div class="app-container flex flex-col">
    <!-- 查询区 -->
    <searchCard @onSearch="searchFn" @onReset="resetFn">
      <el-form :model="SKUForm" label-width="auto" inline @keyup.enter="searchFn">
        <el-form-item label="SKU名称：">
          <pb-input v-model="SKUForm.skuName" placeholder="请输入SKU名称"></pb-input>
        </el-form-item>
        <el-form-item label="SKU编码：">
          <pb-input v-model="SKUForm.skuCode" placeholder="请输入SKU编码或外部、内部编码"></pb-input>
        </el-form-item>

        <el-form-item label="SKU匹配：">
          <pb-check :list="matchList" @change="changeCheck($event, 'match')"></pb-check>
        </el-form-item>
        <el-form-item label="状态：">
          <pb-check :list="staList" @change="changeCheck($event, 'status')"></pb-check>
        </el-form-item>
        <el-form-item label="采购周期：">
          <pb-check :list="PurCycleList" :defaultProps="{ label: 'purchasingCycleName' }"
            @change="changeCheck($event, 'purchasing')"></pb-check>
        </el-form-item>
      </el-form>
    </searchCard>
    <!-- 表格区 -->
    <div class="flex-1">
      <pb-card padding="0" height="100%">
        <div class="content-box">
          <ContentOperation>
            <pb-button size="small" plain class="mr-6" @click="addSku" v-hasPerm="'center:sku:add'">+添加</pb-button>
            <pb-button size="small" plain class="mr-6" v-hasPerm="'center:sku:import'">导入</pb-button>
            <pb-button size="small" plain v-hasPerm="'center:sku:export'">导出</pb-button>
          </ContentOperation>
          <div class="table-box flex">
            <div class="left-tree-box">
              <pb-tree :style="{ maxHeight: treeH }" @nodeClick="nodeClick" :treeData="skuTreeData"
                :defaultProps="treeProps"></pb-tree>
            </div>
            <div class="table-right ">
              <pb-table :column="SKUColumn" :tableData="SKUTableData" :bottomElement="['pb-page']">
                <template #isWeighed="{ row }">
                  <div>{{ row.isWeighed ? '计重' : '计数' }}</div>
                </template>
                <template #enableState="{ row }">
                  <div>{{ row.enableState ? '已上架' : '未上架' }}</div>
                </template>
                <template #operate="{ row }">
                  <div class="flex">
                    <div v-hasPerm="'center:sku:match'">
                      <pb-button size="small" text @click="matchHandler(row)">匹配SPU</pb-button>
                      <p class="divider mr-2 ml-2"></p>
                    </div>
                    <div v-hasPerm="'center:sku:edit'">
                      <pb-button size="small" text @click="editSku(row)" v-hasPerm="'center:sku:edit'">编辑</pb-button>
                      <p class="divider mr-2 ml-2"></p>
                    </div>
                    <div v-hasPerm="'center:sku:enable'">
                      <pb-button size="small" text @click="changeStatus(row)">{{
                        row.enableState ? '下架' : '上架'
                        }}</pb-button>
                      <p class="divider mr-2 ml-2"></p>
                    </div>
                    <!-- v-hasPerm="'center:sku:delete'" -->
                    <PopconfirmButton @confirm="deleteFn(row)"></PopconfirmButton>
                  </div>

                </template>
              </pb-table>
              <pb-pagination v-model:currentPage="pages.currentPage" v-model:pageSize="pages.pageSize"
                @onChange="onPagesChange" :total="pages.total"></pb-pagination>
            </div>
          </div>
        </div>
      </pb-card>
    </div>


    <!-- 添加修改弹窗 -->
    <addModifPop ref="addPopRef" @refresh="resetFn" :purCycle="purCycle"></addModifPop>

    <!-- 匹配SPU弹窗 -->
    <matchSpu ref="matchPopRef" @refresh="resetFn"></matchSpu>
  </div>
</template>

<script setup lang="ts">
  import matchSpu from "./components/matchSpu.vue";
  import addModifPop from "./components/addModifPop.vue";
  import { getSkuInfoList, getPurchasingCycle, getSkuStatue, deleteSku } from "@/api/Sku";
  import { getSkuClassTreeApi } from "@/utils/globalFn";
  import { createMessage } from "@/Public-UIlibrary/pb-message/method";
  const SKUTableData = ref([]);
  const skuTreeData = ref([])
  const SKUColumn = reactive([
    {
      key: "skuCode",
      width: 120,
      name: "SKU编码",
      align: 'right',
    },
    {
      key: "skuClassName",
      width: 120,
      name: "SKU类别",
    },
    {
      key: "skuName",
      width: 150,
      name: "SKU名称",
    },
    {
      key: "accountingUnitName",
      name: "计量单位",
    },
    {
      key: "specifications",
      name: "规格",
    },
    {
      key: "unitWeight",
      name: "单位重量（kg)",
      align: 'right',
      width: 130
    },
    {
      key: "spuCommonlyName",
      name: "匹配SPU",
    },
    {
      slot: "enableState",
      name: "状态",
    },
    {
      key: "brand",
      name: "品牌",
    },
    {
      key: "barCode",
      name: "SKU条码",
    },
    {
      slot: "isWeighed",
      name: "计量方式",
    },
    {
      key: "dataSource",
      name: "来源",

    },
    {
      slot: "operate",
      name: "操作",
      width: 230,
      fixed: "right",
    },
  ]);
  const treeProps = { children: "children", label: "skuClassName" };
  const pageInit = () => ({
    total: 0,
    currentPage: 1,
    pageSize: 15,
  });
  const pages = ref(pageInit());
  const onPagesChange = () => {
    getSkuInfoListApi();
  };


  const matchOrigin = () => [
    { label: "全部", val: null, checked: true },
    { label: "未匹配", val: 0, checked: false },
    { label: "已匹配", val: 1, checked: false },
  ];
  const staOrigin = () => [
    { label: "全部", val: null, checked: true },
    { label: "未上架", val: 0, checked: false },
    { label: "已上架", val: 1, checked: false },
  ];

  const matchList = ref(matchOrigin());
  const staList = ref(staOrigin());
  const formOrigin = () => ({
    skuName: "",
    skuCode: "",
    matchSpu: null,
    purchasingCycle: null,
    enableState: null,
  });
  const SKUForm = ref(formOrigin());

  const searchFn = () => {
    pages.value.currentPage = 1
    getSkuInfoListApi();
  };

  const resetFn = () => {
    pages.value.currentPage = 1;
    SKUForm.value = formOrigin();
    matchList.value = matchOrigin();
    staList.value = staOrigin();
    PurCycleList.value.map((el, idx) => {
      el.checked = false
      if (idx == 0) el.checked = true
    })
    getSkuInfoListApi();
  };


  const changeCheck = (event, type) => {
    if (type == 'match') {
      SKUForm.value.matchSpu = event.val
    } else if (type == 'purchasing') {
      SKUForm.value.purchasingCycle = event.purchasingCycleCode
    } else if (type == 'status') {
      SKUForm.value.enableState = event.val
    }
    getSkuInfoListApi();
  }

  // 选择节点
  const skuClassCode = ref("");
  const nodeClick = ({ curNode }) => {
    console.log(curNode);

    skuClassCode.value = curNode.skuClassCode
    getSkuInfoListApi()
  };

  // 获取sku信息列表
  const getSkuInfoListApi = () => {
    return new Promise < void> ((resolve, reject) => {
      let { currentPage, pageSize } = { ...pages.value };
      let params = {
        currentPage,
        pageSize,
        skuClassCode: skuClassCode.value,
        ...SKUForm.value,
      };
      getSkuInfoList(params).then((res) => {
        if (res.code == 2000) {
          SKUTableData.value = res.data.records;
          pages.value.total = res.data.total;
        }
      });
    });
  };

  const addPopRef = ref(null)
  const addSku = () => {
    addPopRef.value.showFn()
  }

  const editSku = (row) => {
    addPopRef.value.showFn(JSON.parse(JSON.stringify(row)))
  }

  // 切换上下架状态
  const changeStatus = (row) => {
    getSkuStatue({ skuCode: row.skuCode }).then(res => {
      if (res.code == 2000) {
        createMessage({
          message: '操作成功'
        })
        getSkuInfoListApi()
      }
    })
  }

  // 删除sku
  const deleteFn = (row) => {
    deleteSku({ skuId: row.skuId }).then(res => {
      if (res.code == 2000) {
        createMessage({
          message: '操作成功'
        })
        getSkuInfoListApi()
      }
    })
  }
  const matchPopRef = ref(null)
  // 匹配spu
  const matchHandler = (row) => {
    let { skuName, skuCode, spuCommonlyName } = { ...row }
    matchPopRef.value.showFn({ skuName, skuCode, spuCommonlyName })
  }

  // 查询采购周期
  const PurCycleList = ref([
    { purchasingCycleName: "全部", purchasingCycleCode: null, checked: true },
  ])

  const purCycle = ref([])
  const getPurchasingCycleApi = () => {
    return new Promise < void> ((resolve, reject) => {
      getPurchasingCycle().then(res => {
        if (res.code == 2000) {
          purCycle.value = res.data
          let arr = res.data.map(el => {
            el.checked = false
            return el
          })
          PurCycleList.value.push(...arr)
          resolve()
        }
      })
    })
  }

  const treeH = ref(null);
  onMounted(() => {
    getSkuClassTreeApi().then(res => {
      skuTreeData.value = [
        {
          skuClassName: '全部',
          children: res
        }
      ];
      getPurchasingCycleApi().then(res => {
        getSkuInfoListApi()

        var height = document.getElementsByClassName("pb-table");
        treeH.value = height[0].offsetHeight + "px";

        window.addEventListener("resize", () => {
          height = document.getElementsByClassName("pb-table");
          treeH.value = height[0].offsetHeight + "px";
        });
      })
    })
  })
</script>

<style lang="scss" scoped>
  .content-box {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .table-box {
    flex: 1;
    overflow: hidden;

    .table-right {
      width: 84%;
      height: 100%;
      padding: 16px;
      box-sizing: border-box;
    }
  }
</style>